package com.bitcola.security.admin.biz;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.ace.cache.annotation.CacheClear;
import com.bitcola.security.admin.entity.User;
import com.bitcola.security.admin.mapper.ColaUserLimitMapper;
import com.bitcola.security.admin.mapper.ColaUserMapper;
import com.bitcola.security.admin.mapper.MenuMapper;
import com.bitcola.security.admin.mapper.UserMapper;
import com.bitcola.security.auth.client.jwt.UserAuthUtil;
import com.bitcola.security.auth.common.util.EncoderUtil;
import com.bitcola.security.common.biz.BaseBiz;
import com.bitcola.security.common.constant.UserConstant;
import com.bitcola.security.common.msg.TableResultResponse;
import com.bitcola.security.common.util.AdminQuery;
import com.bitcola.entity.ColaUserLimit;
import com.bitcola.security.admin.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * ${DESCRIPTION}
 *
 * @author wx
 * @create 2017-06-08 16:23
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserBiz extends BaseBiz<UserMapper,User> {

    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private UserAuthUtil userAuthUtil;
    @Autowired
    ColaUserMapper userMapper;
    @Autowired
    ColaUserLimitMapper userLimitMapper;
    @Override
    public void insertSelective(User entity) {
        String password = new BCryptPasswordEncoder(UserConstant.PW_ENCORDER_SALT).encode(entity.getPassword());
        entity.setPassword(password);
        Long id = mapper.getMaxId()+1;
        if (id == 100) throw new RuntimeException("管理系统人数已达上限");
        entity.setId(id.toString());
        super.insertSelective(entity);
        // 创建客户账号(id = 邀请人,昵称,头像,时间)
        String nickName = "客服"+entity.getId();
        userMapper.insertCustomer(entity.getId(),nickName,UserConstant.DEFAULT_AVATAR,System.currentTimeMillis());
        // 禁止该用户冲提和交易
        ColaUserLimit userLimit = new ColaUserLimit();
        userLimit.setId(UUID.randomUUID().toString());
        userLimit.setUserId(entity.getId());
        userLimit.setReason("初始化禁用");
        userLimit.setTime(0L);
        userLimit.setType(1);
        userLimit.setModule("community");
        userLimitMapper.insertSelective(userLimit);
        userLimit = new ColaUserLimit();
        userLimit.setId(UUID.randomUUID().toString());
        userLimit.setUserId(entity.getId());
        userLimit.setReason("初始化禁用");
        userLimit.setTime(0L);
        userLimit.setType(1);
        userLimit.setModule("withdraw");
        userLimitMapper.insertSelective(userLimit);
        userLimit = new ColaUserLimit();
        userLimit.setId(UUID.randomUUID().toString());
        userLimit.setUserId(entity.getId());
        userLimit.setReason("初始化禁用");
        userLimit.setTime(0L);
        userLimit.setType(1);
        userLimit.setModule("makeOrder");
        userLimitMapper.insertSelective(userLimit);
    }

    
    @Override
    @CacheClear(pre="user{1.username}")
    public void updateSelectiveById(User entity) {
        super.updateSelectiveById(entity);
    }

    /**
     * 根据用户名获取用户信息
     * @param username
     * @return
     */
    public User getUserByUsername(String username){
        User user = new User();
        user.setUsername(username);
        return mapper.selectOne(user);
    }


    public TableResultResponse<UserVO> page(AdminQuery query) {
        List<UserVO> list = mapper.page(query);
        Long total = mapper.count(query);
        return new TableResultResponse<>(total,list);
    }

    public Boolean updateCipher(String id){
        Boolean bool = Boolean.FALSE;
        //获取用户信息
        User query = new User();
        query.setId( id);
        User user = mapper.selectByPrimaryKey( query);
        //设置默认的资金密码
        String cipher = EncoderUtil.encode( UserConstant.CIPHER);
        if(ObjectUtil.isNotEmpty( user)){
            bool = userMapper.updateCipher( id, cipher) > 0;
        }
        return bool;
    }

    public Boolean updatePassword(String id){
        Boolean bool = Boolean.FALSE;
        //获取用户信息
        User query = new User();
        query.setId( id);
        User user = mapper.selectByPrimaryKey( query);
        //设置默认的登录密码
        String password = EncoderUtil.encode( UserConstant.PASSWORD);
        if(ObjectUtil.isNotEmpty( user)){
            bool = mapper.updatePassword( id, password) > 0;
        }
        return bool;
    }

    public UserVO findUserInfo(String id){
        //个人信息
        return mapper.findUserInfo( id);
    }

    public AssetsVO findUserAssets(AdminQuery query){
        return mapper.findUserAssets( query);
    }

    public TableResultResponse<AssetsFlowVO> findAssetsFlow(AdminQuery query){
        //列表
        List<AssetsFlowVO> list = mapper.findAssetsFlow( query);
        //总条数
        Long total = mapper.countAssetsFlow( query);
        return new TableResultResponse<>( total, list);
    }

    public List<AssetsStatisticsVO> assetsStatistics(AdminQuery query){
        //列表
        return mapper.assetsStatistics( query);
    }

    public TeamVO findTeam(String id){
        TeamVO vo = new TeamVO();
        //上级用户id
        Integer pid = mapper.findUserPid( id);
        vo.setPid( pid);
        //直推用户列表
        List<UserVO> direct  = mapper.findDirectList( id);
        vo.setDirect( direct);
        return vo;
    }

    @Transactional( rollbackFor = Exception.class)
    public Boolean limit(Map<String, Object> data){
        Integer k = 0;
        //先删除当前用户的所有禁止
        k = mapper.deleteUserLimit( StrUtil.toString( data.get( UserConstant.USER_ID)));
        //获取所有的禁止权限
        List<String> list = (List<String>)data.get( UserConstant.LIST);
        if(CollUtil.isNotEmpty( list)) {
            //遍历
            for(int idx = 0; idx < list.size(); idx ++){
                ColaUserLimit  limit = new ColaUserLimit();
                limit.setId( StrUtil.toString(System.nanoTime()));
                limit.setUserId( StrUtil.toString( data.get( UserConstant.USER_ID)));
                limit.setTime( System.currentTimeMillis());
                limit.setType( 1);
                limit.setModule( list.get( idx));
                //添加
                k = mapper.addUserLimit( limit);
            }
        }
        return k > 0;
    }

    public List<String> findLimitList(String id){
        return userLimitMapper.findLimitList( id);
    }
}
